﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;

namespace Warehouse_Management
{
    public class Global
    {

        public static DataTable DVT_dt { get; set; }
        public static XmlDocument Config { get; set; }

        public static string Skin { get; set; }

        public static string PASS { get; set; }

        public static string SERVER_NAME { get; set; }

        public static string USER { get; set; }

        public static string DATABASE_NAME { get; set; }

        public static List<string> ListTableNameSource;

        public Global()
        {
        }
        public static void Start()
        {
            //LoadDVT();
            LoadConfig();
            LoadConfigData();
        }

        public static string ReadNodeXmlAppSettings(string key)
        {
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(config.FilePath);
            string groupSettingName = "applicationSettings";

            return ReadNodeXml(config, doc, groupSettingName, key);
        }
        public static string ReadNodeXml(System.Configuration.Configuration config, System.Xml.XmlDocument xmlDocument, string groupSettingName, string key)
        {
            string result = "";

            try
            {
                result = xmlDocument.SelectSingleNode("//" + groupSettingName + "//add[@key='" + key + "']").SelectSingleNode("@value").Value;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }//Logger.LocalLogger.Instance().WriteMessage(key, ex); }

            return result;
        }
        public static void SaveNodeXmlAppSettings(string key, object value)
        {
            try
            {
                System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(config.FilePath);
                string groupSettingName = "applicationSettings";

                SaveNodeXml(config, doc, groupSettingName, key, value);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }//Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        public static void SaveNodeXml(System.Configuration.Configuration config, System.Xml.XmlDocument xmlDocument, string groupSettingName, string key, object value)
        {
            try
            {
                xmlDocument.SelectSingleNode("//" + groupSettingName + "//add[@key='" + key + "']").SelectSingleNode("@value").Value = value.ToString();
                xmlDocument.Save(config.FilePath);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }//Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
#region Config skin
        public static void LoadConfig()
        {
            Config = new System.Xml.XmlDocument();
            Config.Load(Application.StartupPath + "\\config.xml");

            XmlNode xmlSkin = Config.SelectSingleNode("Root/Skin");
            Skin = xmlSkin.InnerText;
        }
        public static void SaveConfig(string nameConfig, string value)
        {
            XmlNode node = Config.SelectSingleNode("Root/" + nameConfig);
            if (node != null)
                node.InnerText = value;
            else
            {
                XmlNode newnode = Config.CreateNode("string", nameConfig, "");
                newnode.InnerText = value;
                Config.AppendChild(newnode);
            }
            Config.Save("Config.xml");
        }
#endregion


        #region ĐVT
        public static string getDVT(string ten)
        {
            DataRow[] items = DVT_dt.Select(string.Format("Ten = '{0}'", ten.Trim().ToUpper()));
            if (items.Length == 0) return string.Empty;
            return items[0][0].ToString();
        }
        public static string getDVTByMa(string Ma)
        {
            DataRow[] items = DVT_dt.Select(string.Format("Ma = '{0}'", Ma.Trim().ToUpper()));
            if (items.Length == 0) return string.Empty;
            return items[0][1].ToString();
        }
        public static void LoadDVT()
        {
            DVT_dt = DonViTinh.SelectAll().Tables[0];
        }
 #endregion

        #region Database
        static SqlConnection sqlConnection = new SqlConnection();
        /// <summary>
        /// Initializes the field 'server'
        /// </summary>
        public static void InitializeServer(string sqlConnectionString)
        {
            // To Connect to our SQL Server - we Can use the Connection from the System.Data.SqlClient Namespace.
            sqlConnection = new SqlConnection(sqlConnectionString);

            //build a "serverConnection" with the information of the "sqlConnection"
            //Microsoft.SqlServer.Management.Common.ServerConnection serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);

            //The "serverConnection is used in the ctor of the Server.
            //server = new Server(serverConnection);
        }

        public static List<string> ListDatabases()
        {
            List<string> listData = new List<string>();
            DataTable dtSource = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter();
            string query = "SELECT name FROM sys.sysdatabases";
            adapter.SelectCommand = new SqlCommand(query, sqlConnection);
            adapter.Fill(dtSource);
            foreach (DataRow dr in dtSource.Rows)
            {
                listData.Add(dr[0].ToString());
            }
            return listData;
        }
        public static void SaveNodeXmlConnectionStrings(string connectionString)
        {
            
                //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                //System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                //doc.Load(config.FilePath);
                //doc.SelectSingleNode("//connectionStrings").ChildNodes[0].Attributes[1].Value = connectionString;
                //doc.Save(config.FilePath);

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings["MSSQL"].ConnectionString = connectionString;
                config.Save(ConfigurationSaveMode.Modified);
            
        }
        public static string ReadNodeXmlConnectionStrings2()
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                string connectionString = config.ConnectionStrings.ConnectionStrings["MSSQL"].ConnectionString;

                return connectionString;
            }
            catch  {  }

            return string.Empty;
        }
        public static void LoadConfigData()
        {
            string connection = ReadNodeXmlConnectionStrings2();
            string[] slipt = connection.Split(';');
            foreach (string item in slipt)
            {
                if (item.ToUpper().Contains("Server".ToUpper()))
                {
                    SERVER_NAME = item.Split('=')[1];
                }
                else if (item.ToUpper().Contains("Database".ToUpper()))
                {
                    DATABASE_NAME = item.Split('=')[1];
                }
                else if (item.ToUpper().Contains("uid".ToUpper()))
                {
                    USER = item.Split('=')[1];
                }
                else if (item.ToUpper().Contains("pwd".ToUpper()))
                {
                    PASS = item.Split('=')[1];
                }
            }
        }
        #endregion
    }
   
}
